<?php
/**
 * 晨会、早课管理列表
 */
namespace App\Http\Controllers\Api;
use App\Model\Area;
use App\Model\Meet;
use App\Model\Stock;
use App\Model\MaterialList;
use App\Model\WarehouseMaterials;
use App\Model\Checkcategory;
use App\Model\Company;
use App\Model\WarehouseOrder;
use App\Model\WarehouseOutboundDetail;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpWord\TemplateProcessor;

class MeetController extends Controller
{

    /**
     * 晨会、早课管理列表数据操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function listdata(Request $request)
    {
        $query = $this->pub($request);
        $res=$query->paginate($request->get('limit',15))->toArray();

        $res_arr['data']['list'] = $res['data'];
        $res_arr['data']['count'] = $res['total'];
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 导出晨会、早课管理列表
     * @param $request
     * @return array
     */
    public function pub($request){
        $query= Meet::with([
            'company:id,comName,community,address',
            'company.place_5:id,name',
            'Users:id,name'])->orderby('id','asc');
        if(isset($request['company_id']) && $company_id = $request['company_id']){ //企业id
            $query->where('company_id',$company_id);
        }
        /*if(isset($request['community']) && $community = $request['community']){ //所属社区
            $query->whereHas('company', function ($q) use ($community) {
                $q->where('community', $community);
            });
        }*/
        /*if(isset($request['comname']) && $comname = $request['comname']){ //单位名称
            $query->whereHas('company', function ($q) use ($comname) {
                $q->orWhere('comName','like','%'.$comname.'%')->orWhere('address','like','%'.$comname.'%');
            });
        }*/
        if(isset($request['start_created_at']) && $start_created_at = $request['start_created_at']){  //开始时间
            $query->where('created_at','>=',$start_created_at);
        }else{
            $query->where('created_at','>=',date('Y-m-d')." 00:00:00");
        }
        if(isset($request['end_created_at']) && $end_created_at = $request['end_created_at']){  //结束时间
            $query->where('created_at','<=',$end_created_at);
        }else{
            $query->where('created_at','<=',date('Y-m-d')." 23:59:59");
        }
        return $query;
    }

    /**
     * 导出晨会、早课管理列表
     * @param Request $request
     * @return void
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function exportone(Request $request)
    {
        $query = $this->warehouseMaterialspub($request);
        $dataExpor= $query->get()->toArray();

        $excel = new \PHPExcel();
        $excel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objActSheet = $excel->getActiveSheet();
        $letter = array('A','B','C','D','E','F','G','H','I');
        $title = [
            'A1'=>'序 号',
            'B1'=>'企业名称',
            'C1'=>'所属社区',
            'D1'=>'视频或者照片',
            'E1'=>'日 期',
            'F1'=>'内 容',
            'G1'=>'备 注',
            'I1'=>'提交人',
        ];
        foreach ($title as $tk=>$tv){
            $objActSheet->setCellValue($tk,$tv);
        }

        foreach ($letter as $l){
            $objActSheet->getStyle($l.'1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
        }

        /**填充内容*/
        $orirow = 2;
        $i = 1;

        foreach ($dataExpor as &$val) {
            $objActSheet->setCellValue("A".$orirow,$i);
            $objActSheet->setCellValue("B".$orirow,$val['checkcategory_id']??'');
            $objActSheet->setCellValue("C".$orirow,$val['company_id']??'');
            $objActSheet->setCellValue("D".$orirow,$val['goods_name']??'');
            $objActSheet->setCellValue("E".$orirow,$val['name']??'');
            $objActSheet->setCellValue("F".$orirow,$val['income_warehouse']??'');
            $objActSheet->setCellValue("G".$orirow,$val['warehouse']??'');
            $objActSheet->setCellValue("H".$orirow,$val['leave_warehouse']??'');
            $objActSheet->setCellValue("I".$orirow,$val['loss_warehouse']??'');
            $objActSheet->setCellValue("J".$orirow,$val['address']??'');
            $objActSheet->setCellValue("K".$orirow,$val['leader']??'');
            $objActSheet->setCellValue("L".$orirow,$val['leaderPhone']??'');

            $i ++;
            $orirow ++;

        }
        /**填充内容*/
        //统一设置填充内容左右居中、字号、宽度
        foreach ($letter as $l){
            for ($x = 2;$x<=$orirow;$x++){
                /*$objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
                $objActSheet->getStyle($l.'2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中*/
                if($l=='A'){
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_CENTER;
                }else{
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_LEFT;
                }
                $objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal($setHorizontal);
                $objActSheet->getStyle($l.$x)->getFont()->setSize(10);
                $objActSheet->getColumnDimension($l)->setWidth(20);

            }

        }
        /*$objActSheet->getColumnDimension('B')->setWidth(50);
        $objActSheet->getColumnDimension('C')->setWidth(50);
        $objActSheet->getColumnDimension('J')->setWidth(50);*/
        for ($x=1; $x<=($orirow); $x++) {
            $objActSheet->getRowDimension($x)->setRowHeight(30);//统一设置行高度

        }
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
                ),
            ),
        );
        $objActSheet->getStyle('A1:G1'.($orirow))->applyFromArray($styleArray);//设置粗边框


        $write = new \PHPExcel_Writer_Excel5($excel);
        ob_end_clean();
        //$date = Carbon::now()->toDateString();//表名前缀日期
        $date=time();
        $filename = '物资库存管理表-'.$date;
        $path = '/storage/excel/'.$filename.'.xls';
        $res = $write->save(public_path().$path);
        return response()->json(['code'=>0,'msg'=>'导出成功','url'=>'http://'.$_SERVER['HTTP_HOST'].$path,'file_name'=>$filename]);
    }

    /**
     * 晨会、早课管理页面
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function referweb(Request $request)
    {
        //修改的话该值有值
        $id = isset($request['id']) ? $request['id'] : 0;  //入库单id
        $meet = Meet::with([
            'company:id,comName,community,address',
            'company.place_5:id,name',
            'Users:id,name'])->where('id', $id)->first();
        if(!$meet){
            $res_arr["code"] = 408;
            $res_arr["message"] = '该晨会、早课不存在，不能修改';
            return response()->json($res_arr);
        }
        $meet = $meet->toArray();
        $res_arr['data'] = $meet;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 晨会、早课管理数据处理
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function meetsdo(Request $request)
    {
        $redata = $request->all();
        $id = isset($redata['id']) ? $redata['id'] : 0;
        $data = Meet::where('id',$id)->first();
        unset($redata['_token']);
        if($data){
            $res = Meet::where('id', $id)->update($redata);
        }else{
            unset($redata['id']);
            $user = Auth::user();
            $uid = $user->id;
            $companyId = $user->companyId;
            $redata['company_id'] = $companyId;
            $redata['user_id'] = $uid;
            $redata['created_at'] = date('Y-m-d H:i:s');
            $res = Meet::insertGetId($redata);
        }
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 晨会、早课删除
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function del(Request $request)
    {
        $redata = $request->all();
        $id = isset($redata['id']) ? $redata['id'] : 0;
        $data = Meet::where('id',$id)->first();
        if(empty($data)){
            $res_arr["code"] = 408;
            $res_arr["message"] = '该晨会、早课记录不存在，不能删除';
            return response()->json($res_arr);
        }
        $resu = Meet::where('id', $id)->delete();
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 北宅街道下面的社区
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function comlist_pro(Request $request)
    {
        $tree = array();
        $area_first = array();
        $area_first = Area::where('name','北宅街道')->first()->toArray();
        $tree = $area_first;
        $where = array();
        $where[] = array('pid', $area_first['id']);
        $area = Area::where($where)->select(array('id','pid','node','name','level'));
        if(isset($request['name']) && $name = $request['name']){  //社区名称
            $area=$area->where('name','like','%'.$name.'%');
        }
        $area = $area->get()->toArray();
        $tree['street'] = $area;

        $res_arr['data']['street'] = $area;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 晨会、早课管理列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function comlistdata(Request $request)
    {
        $start_created_at = $request['start_created_at']??'';
        $end_created_at = $request['end_created_at']??'';
        $query = $this->compub($request);
        $meetque = Meet::select('id','company_id','url','remarks','created_at');
        if($start_created_at || $end_created_at){  //开始时间
            if($start_created_at){  //开始时间
                $meetque = $meetque->where('created_at','>=',$start_created_at." 00:00:00");
            }

            if($end_created_at){  //结束时间
                $meetque = $meetque->where('created_at','<=',$end_created_at." 23:59:59");
            }
        }else{
            $meetque = $meetque->where('created_at','>=',date('Y-m-d')." 00:00:00")->where('created_at','<=',date('Y-m-d')." 23:59:59");
            $meetque = $meetque->limit(1);
            $meetque = $meetque->orderby('created_at','desc');
        }
        if(isset($request['community']) && $community = $request['community']){ //所属社区
            $query = $query->where('community', $community);
        }
        $meetque = $meetque->get()->toArray();
        $meetarr = [];
        foreach ($meetque as $mk=>$mv){
            $meetarr[$mv['company_id']][] = $mv;
        }
        if($meetarr){
            $companyids = array_column($meetque,'company_id');
            $query = $query->whereIn('id', $companyids);
            $res=$query->paginate($request->get('limit',15))->toArray();
            foreach ($res['data'] as $key=>$val){
                if(isset($meetarr[$val['id']])){
                    $res['data'][$key]['meet'] = $meetarr[$val['id']];
                }else{
                    $res['data'][$key]['meet'] = [];
                }
            }
        }else{
            $res['data']=[];
            $res['total']=0;
        }


        $res_arr['data']['list'] = $res['data'];
        $res_arr['data']['count'] = $res['total'];
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 导出晨会、早课管理列表
     * @param $request
     * @return array
     */
    public function compub($request){
        $query= Company::with([
            'place_5:id,name'])->select('id','comName','community','address')->orderby('id','asc');
        if(isset($request['comname']) && $comname = $request['comname']){ //单位名称或者单位地址
            $query->orWhere('comName','like','%'.$comname.'%')->orWhere('address','like','%'.$comname.'%');
        }
        return $query;
    }

    /**
     * 导出晨会、早课管理列表
     * @param Request $request
     * @return void
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function comexportone(Request $request)
    {
        $query = $this->compub($request);
        $dataExpor= $query->get()->toArray();
        $start_created_at = $request['start_created_at']??'';
        $end_created_at = $request['end_created_at']??'';
        $meetque = Meet::select('id','company_id','url','remarks','created_at');
        if($start_created_at || $end_created_at){  //开始时间
            if($start_created_at){  //开始时间
                $meetque = $meetque->where('created_at','>=',$start_created_at." 00:00:00");
            }

            if($end_created_at){  //结束时间
                $meetque = $meetque->where('created_at','<=',$end_created_at." 23:59:59");
            }
        }else{
            $meetque = $meetque->where('created_at','>=',date('Y-m-d')." 00:00:00")->where('created_at','<=',date('Y-m-d')." 23:59:59");
            $meetque = $meetque->limit(1);
            $meetque = $meetque->orderby('created_at','desc');
        }
        $meetque = $meetque->get()->toArray();
        $meetarr = [];
        foreach ($meetque as $mk=>$mv){
            $meetarr[$mv['company_id']][] = $mv;
        }
        foreach ($dataExpor as $key=>$val){
            if(isset($meetarr[$val['id']])){
                $dataExpor[$key]['meet'] = $meetarr[$val['id']];
            }else{
                $dataExpor[$key]['meet'] = [];
            }
        }
        $excel = new \PHPExcel();
        $excel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objActSheet = $excel->getActiveSheet();
        $letter = array('A','B','C','D','E','F','G');
        $title = [
            'A1'=>'序 号',
            'B1'=>'名 称',
            'C1'=>'社 区',
            'D1'=>'地 址',
            'E1'=>'视频/照片',
            'F1'=>'备 注',
            'G1'=>'提交时间',
        ];
        foreach ($title as $tk=>$tv){
            $objActSheet->setCellValue($tk,$tv);
        }

        foreach ($letter as $l){
            $objActSheet->getStyle($l.'1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
        }

        /**填充内容*/
        $orirow = 2;
        $i = 1;

        foreach ($dataExpor as $k=>$val) {
            $objActSheet->setCellValue("A".$orirow,$i);
            $objActSheet->setCellValue("B".$orirow,$val['comName']??'');
            $objActSheet->setCellValue("C".$orirow,$val['place_5']['name']??'');
            $objActSheet->setCellValue("D".$orirow,$val['address']??'');

            if(isset($val['meet'])){
                $cou = count($val['meet']);
                if($cou>1){
                    $h = $cou+$orirow-1;
                    $objActSheet->mergeCells("A".$orirow.":"."A".$h);
                    $objActSheet->mergeCells("B".$orirow.":"."B".$h);
                    $objActSheet->mergeCells("C".$orirow.":"."C".$h);
                    $objActSheet->mergeCells("D".$orirow.":"."D".$h);
                }
                foreach ($val['meet'] as $mk=>$mv){
                    $objActSheet->setCellValue("E".$orirow,$mv['url']??'');
                    $objActSheet->setCellValue("F".$orirow,$mv['remarks']??'');
                    $objActSheet->setCellValue("G".$orirow,$mv['created_at']??'');
                    $orirow ++;
                }
                if($cou<1){
                    $orirow ++;
                }
            }
            $i ++;
        }
        /**填充内容*/
        //统一设置填充内容左右居中、字号、宽度
        foreach ($letter as $l){
            for ($x = 2;$x<=$orirow;$x++){
                /*$objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
                $objActSheet->getStyle($l.'2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中*/
                if($l=='A'){
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_CENTER;
                }else{
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_LEFT;
                }
                $objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal($setHorizontal);
                $objActSheet->getStyle($l.$x)->getFont()->setSize(10);
                $objActSheet->getColumnDimension($l)->setWidth(20);

            }

        }
        /*$objActSheet->getColumnDimension('B')->setWidth(50);
        $objActSheet->getColumnDimension('C')->setWidth(50);
        $objActSheet->getColumnDimension('J')->setWidth(50);*/
        for ($x=1; $x<=($orirow); $x++) {
            $objActSheet->getRowDimension($x)->setRowHeight(30);//统一设置行高度

        }
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
                ),
            ),
        );
        $objActSheet->getStyle('A1:G1'.($orirow))->applyFromArray($styleArray);//设置粗边框


        $write = new \PHPExcel_Writer_Excel5($excel);
        ob_end_clean();
        //$date = Carbon::now()->toDateString();//表名前缀日期
        $date=time();
        $filename = '晨会早课表-'.$date;
        $path = '/storage/excel/'.$filename.'.xls';
        $res = $write->save(public_path().$path);
        return response()->json(['code'=>0,'msg'=>'导出成功','url'=>'http://'.$_SERVER['HTTP_HOST'].$path,'file_name'=>$filename]);
    }

    /**
     * 我的晨会、早课管理列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function meetlistdata(Request $request)
    {
        $user = Auth::user();
        $uid = $user->id;
        $query = Meet::with([
            'company:id,comName,community,address','company.place_5:id,name'])->select('id','company_id','url','video','remarks','created_at')->where('user_id',$uid);
        $query = $query->orderby('id','desc');
        $res=$query->paginate($request->get('limit',15))->toArray();

        $res_arr['data']['list'] = $res['data'];
        $res_arr['data']['count'] = $res['total'];
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }
}
